﻿using System;
using System.Net;
using System.Net.Sockets;

namespace SharpSNSTest
{
    public class SimpleAsyncSocket
    {
        public event EventHandler Closed;
        public event EventHandler<DataReceivedEventArgs> DataReceived;

        public class DataReceivedEventArgs : EventArgs
        {
            public byte[] DataBuffer;
            public DataReceivedEventArgs(byte[] buffer, int numBytes)
            {
                DataBuffer = new byte[numBytes];
                Buffer.BlockCopy(buffer, 0, DataBuffer, 0, numBytes);
            }
        }

        private class ReceiveStateObject
        {
            public byte[] Buffer = new byte[1024];
        }

        private Socket _clientSock;
        public SimpleAsyncSocket()
        {
            _clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Connect(string host, int port)
        {
            _clientSock.Connect(host, port);
            ReceiveStateObject rso = new ReceiveStateObject();
            _clientSock.BeginReceive(rso.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), rso);
        }

        public void SendData(byte[] data)
        {
            _clientSock.Send(data);
        }

        private void OnReceive(IAsyncResult ar)
        {
            int numBytes = _clientSock.EndReceive(ar);

            if (numBytes > 0)
            {
                ReceiveStateObject rso = ar.AsyncState as ReceiveStateObject;
                if (DataReceived != null)
                    DataReceived(this, new DataReceivedEventArgs(rso.Buffer, numBytes));
                rso = new ReceiveStateObject();
                _clientSock.BeginReceive(rso.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), rso);
            }
            else
                if (Closed != null)
                    Closed(this, EventArgs.Empty);
            
        }
    }
}
